<template>
  <div class="login">
    <!-- 主页面 -->
    <div class="common-layout">
      <el-container>
        <el-header>
          <el-row :gutter="20" justify="space-between" align="middle">
            <el-col :span="16">
              <div class="logo"></div>
            </el-col>
            <el-col :span="4">
              <RouterLink to="/main" class="link link-attr">
                进入主页
                <el-icon>
                  <House />
                </el-icon>
              </RouterLink>
            </el-col>
          </el-row>
        </el-header>
        <el-main>
          <el-row>
            <!-- 登录框 -->
            <el-col :offset="16" :span="4">
              <div class="loginEnter">
                <el-text class="mx-1" size="large">登录</el-text>
                <el-form
                  label-width="auto"
                  :model="countInfoLogin"
                  style="width: 250px"
                  ref="formLogin"
                  :rules="rules">
                  <el-form-item label="帐号" prop="username">
                    <el-input v-model="countInfoLogin.username" placeholder="请输入你的帐号" />
                  </el-form-item>
                  <el-form-item label="密码" prop="password">
                    <el-input
                      v-model="countInfoLogin.password"
                      type="password"
                      show-password
                      placeholder="请输入你的密码"
                      @keyup.enter="login" />
                  </el-form-item>
                  <el-checkbox v-model="checked" label="我已同意服务条款" size="large" />
                  <el-form-item>
                    <el-button type="primary" @click="login" style="width: 250px">登录</el-button>
                  </el-form-item>
                </el-form>
                <div class="link link-small" @click="dialogVisible = true">注册帐号</div>
              </div>
            </el-col>
          </el-row>
        </el-main>
        <el-footer>
          <el-row :gutter="20">
            <el-col :span="2" :offset="8">
              <RouterLink to="/serviceTerms" class="link">服务条款</RouterLink>
            </el-col>
            <el-col :span="2">
              <RouterLink to="/helpCenter" class="link">帮助中心</RouterLink>
            </el-col>
            <el-col :span="2">
              <RouterLink to="/afterSale" class="link">售后服务</RouterLink>
            </el-col>
            <el-col :span="2">
              <RouterLink to="/deliverGoods" class="link">发货与配送</RouterLink>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="5" :offset="10">
              <el-text class="mx-1">CopyRight &copy; 品优购</el-text>
            </el-col>
          </el-row>
        </el-footer>
      </el-container>
    </div>
    <!-- 对话框 -->
    <el-dialog v-model="dialogVisible" title="注册帐号" width="500">
      <el-steps style="max-width: 600px" :active="active" finish-status="success">
        <el-step title="基础信息" />
        <el-step title="其他信息" />
        <el-step title="注册成功" />
      </el-steps>
      <!-- 基本信息 -->
      <el-form
        v-if="active == 0"
        label-width="auto"
        :model="countInfo"
        style="width: 350px"
        ref="formSign"
        :rules="rules">
        <el-form-item label="帐号" prop="username">
          <el-input v-model="countInfo.username" placeholder="请输入你的帐号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="countInfo.password"
            type="password"
            show-password
            placeholder="请输入你的密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="rePassword">
          <el-input
            v-model="countInfo.rePassword"
            type="password"
            show-password
            placeholder="确认你的密码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="countInfo.email" placeholder="确认你的邮箱" />
        </el-form-item>
      </el-form>
      <!-- 更多信息 -->
      <el-form
        v-if="active == 1"
        label-width="auto"
        :model="countInfo"
        style="width: 350px"
        ref="form"
        :rules="rules">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="countInfo.name" placeholder="请输入你的用户名" />
        </el-form-item>
        <el-form-item>
          <span class="demonstration">性别 &nbsp;</span>
          <el-radio v-model="countInfo.gender" value="1">男</el-radio>
          <el-radio v-model="countInfo.gender" value="0">女</el-radio>
        </el-form-item>
        <el-form-item>
          <span class="demonstration">出生日期&nbsp;</span>
          <el-date-picker v-model="countInfo.birthday" type="datetime" placeholder="出生日期" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="countInfo.phone" placeholder="请输入你的电话" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="countInfo.address" placeholder="请输入你的住址" />
        </el-form-item>
      </el-form>
      <div v-if="active == 2" class="success-info">
        <i class="iconfont icon-wancheng1 icon-wancheng-position"></i>
        <br />
        <span>注册成功</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="sign">{{ active < 2 ? '下一步' : '确定' }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
import { loginCount, saveUserInfo, signCount } from '@/api/login'
import { getMoney } from '@/api/personInfo'

const router = useRouter()

// 正则校验
const regex = {
  emailRegex:
    /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
  addressRegex: /^[^\r\n]{1,40}$/,
  phoneRegex: /^\+?[1-9]\d{1,14}(\(\d{1,3}\)|\s?\d{1,3})?[-.\s]?\d{1,14}$/
}

// 创建用户信息仓库
const userStore = useUserStore()

// 关联注册表单
const formSign = ref()

// 关联注册表单2
const form = ref()

// 关联登录表单
const formLogin = ref()

// 对话框显示/隐藏
const dialogVisible = ref(false)

// 步骤条信息
const active = ref(0)

// 登录信息
const countInfoLogin = ref({
  username: '',
  password: ''
})

// 账号信息
const countInfo = ref({
  username: '',
  password: '',
  rePassword: '',
  name: '',
  email: '',
  gender: '1',
  birthday: '',
  phone: '',
  address: '',
  money: 1000
})

// 表单校验
const rules = {
  username: [
    { required: true, message: '请输入帐号', trigger: 'blur' },
    { min: 6, max: 15, message: '帐号必须是6-15位字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    }
  ],
  rePassword: [
    { required: true, message: '请重复输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== countInfo.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 20, message: '用户名必须是1-20位字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      pattern: regex.emailRegex,
      message: '请按照正确的格式输入邮箱',
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入正确的手机号', trigger: 'blur' },
    {
      pattern: regex.phoneRegex,
      message: '请按照正确的格式输入手机号',
      trigger: 'blur'
    }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' },
    {
      pattern: regex.addressRegex,
      message: '不能超过40个字符',
      trigger: 'blur'
    }
  ]
}

// 同意条款
const checked = ref(true)

// 登录
const login = async () => {
  await formLogin.value.validate()
  const res = (await loginCount(countInfoLogin.value)).data
  const field = JSON.parse(JSON.stringify(res.data))
  // 获取键
  const keyArr = []
  for (let key in field) {
    keyArr.push(key)
  }
  const token = keyArr[0]
  if (!token) {
    ElMessage.error(res.msg)
    return
  }
  const money = (await getMoney(res.data[token].id)).data.data
  const userInfo = {
    ...res.data[token],
    money: money,
    username: countInfoLogin.value.username,
    password: countInfoLogin.value.password
  }
  userStore.setToken(token)
  userStore.setUserInfo(userInfo)

  router.replace('/')
}

// 置空表单
const makeEmptyCountInfo = () => {
  countInfo.value = {
    username: '',
    password: '',
    rePassword: '',
    name: '',
    email: '',
    gender: '1',
    birthday: '',
    phone: '',
    address: ''
  }
}

// 注册
const sign = async () => {
  if (active.value < 1) {
    await formSign.value.validate()
    active.value++
  } else if (active.value < 2) {
    await form.value.validate()
    try {
      // 注册帐号
      const resCount = (await signCount(countInfo.value)).data
      // 保存用户信息
      const resSave = (await saveUserInfo(resCount, countInfo.value)).data
      if (resSave.code == 200) {
        active.value++
      } else {
        ElMessage.error(`注册失败，${resCount.msg ? resCount.msg : '请检查各项信息'}`)
      }
    } catch (e) {
      ElMessage.error(`服务器繁忙，请稍后重试`)
    }
  } else {
    makeEmptyCountInfo()
    active.value = 0
    dialogVisible.value = false
  }
}

// 取消输入
const cancel = () => {
  active.value = 0
  dialogVisible.value = false
  makeEmptyCountInfo()
}
</script>

<style scoped>
.login {
  max-width: 1500px;
  display: flex;
  flex-direction: column;
  margin: 0 auto;
}

.el-header {
  height: 80px;
}

.link-attr {
  height: 100px;
  margin-top: 50px;
}

.el-main {
  height: 600px;
  background: url('@/assets/login-bg.png') no-repeat 0px 50px;
  background-color: white;
  margin-bottom: 20px;
  padding-top: 50px;
}

.loginEnter {
  margin-top: 60px;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: first baseline;
  gap: 10px;
  width: 300px;
  height: 310px;
  background-color: white;
  box-shadow: -3px 3px 20px -5px rgba(0, 0, 0, 0.75);
}

.mx-1 {
  position: relative;
  top: 10px;
}

.link-small {
  font-size: 14px;
  margin-right: -180px;
  cursor: pointer;
}

.el-form {
  margin-top: 30px;
}

.success-info {
  text-align: center;
  font-size: 22px;
  color: green;
  margin: 10px 0 10px 0;
}

.icon-wancheng-position {
  font-size: 100px;
}
</style>
